﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace SCResources.DataLayer
{
    internal class IO_IMDB
    {
        public static string getPic(string title)
        {
            HttpWebRequest request =
                (HttpWebRequest)
                WebRequest.Create("http://www.imdbapi.com/?t=" + HttpUtility.HtmlEncode(title) + "&r=xml");

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                return "NULL";
            }

            string returnString = "NULL";
            
            using(Stream resStream = response.GetResponseStream())
            {
                byte[] buffer = new byte[512];
                int count = 0;
                StringBuilder sb = new StringBuilder();

                do
                {
                    count = resStream.Read(buffer, 0, buffer.Length);

                    if(count != 0)
                    {
                        sb.Append(Encoding.ASCII.GetString(buffer, 0, count));
                    }

                } while (count > 0);

                returnString = sb.ToString();
                int startIndex = returnString.IndexOf("poster=\"") + 8; // add the length of poster=\"
                int endIndex = returnString.IndexOf("\" runtime");

                if(startIndex < 10 || endIndex < 10)
                {
                    returnString = "NULL";
                }
                else
                {
                    char[] resultChars = new char[endIndex - startIndex];
                    returnString.CopyTo(startIndex, resultChars, 0, endIndex - startIndex);

                    returnString = new string(resultChars);
                }
            }
            if(returnString.Equals("N/A"))
            {
                return "NULL";
            }
            else
            {
                return returnString;
            }
        }

        public static MemoryStream DownloadCover(string coverUrl)
        {
            // Create web client simulating IE6.
            using (WebClient client = new WebClient())
            {
                client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" +
                " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

                // Download data.
                byte[] arr = client.DownloadData(coverUrl);

                MemoryStream picStream = new MemoryStream(arr);
                return picStream;
            }
        }
    }
}
